import axios from 'axios';
import { Message } from 'element-ui';
import store from '@/store';
import router from './../router';
import { removeEmptyField } from './util';
import { showFullScreenLoading, tryHideFullScreenLoading } from '@/utils/loading';

// create an axios instance
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '/webapi' : '/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
});

// request interceptor
service.interceptors.request.use(
  async (config) => {
    console.log('local', localStorage.ak);
    if (!store.getters.token) store.commit('user/SET_TOKEN', localStorage.ak);
    if (store.getters.token) {
      config.url =
        config.url.indexOf('?') === -1
          ? config.url + '?ak=' + store.getters.token
          : config.url + '&ak=' + store.getters.token;
    }
    if ((config.method === 'get' || config.method == 'GET') && !config.params?.notPagination) {
      config.url =
        config.url.indexOf('?') === -1
          ? config.url + '?page_num=' + store.getters.paging.num + '&page_count=' + store.getters.paging.size
          : config.url + '&page_num=' + store.getters.paging.num + '&page_count=' + store.getters.paging.size;
    }
    if (config.method.toLocaleUpperCase() === 'POST' && !(config.data instanceof FormData)) {
      // 仅对post方式传参的参数做空值过滤
      config.data = removeEmptyField(config.data);
    }
    showFullScreenLoading();
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    tryHideFullScreenLoading();
    if (response.request.responseType) {
      return response.data;
    }
    const res = response.data;
    if (res.status !== undefined) {
      if (res.status === '$SUCCESS') {
        if (res.result.item_list && Object.prototype.toString.call(res.result.item_list) === '[object Object]') {
          res.result.item_list = [];
        }
        return res.result;
      } else {
        return Promise.reject(res);
      }
    }
  },
  async (error) => {
    console.log(error); // for debug
    tryHideFullScreenLoading();
    if (error == 'Error: Request failed with status code 403') {
      window.localStorage.removeItem('userinfo');
      window.localStorage.removeItem('ak');
      store.commit('user/SET_TOKEN', '');
      router.push('/');
    }
    Message.error((error.response && error.response.data.message) || error.message);
    return Promise.reject(error);
  }
);

export default service;
